package main

import (
	"log"
	"net/http"
	"os"
	"reflect"
	"strconv"
	"sync"
	"time"
	"unsafe"

	"./middleware"
	"./router"
	"github.com/tungyao/cedar"
)

var (
	mux   sync.RWMutex
	LIMIT *os.File
)

func init() {
	var err error
	LIMIT, err = os.OpenFile("./log/limit_"+strconv.Itoa(time.Now().Year())+"_"+time.Now().Month().String()+"_"+strconv.Itoa(time.Now().Day()), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 666)
	if err != nil {
		log.Panicln(err)
	}
}
func main() {
	r := cedar.NewRouter("localhost", "localhost")
	r.GlobalFunc("limit", func(w http.ResponseWriter, r *http.Request, co *cedar.Core) error {
		mux.RLock()
		defer mux.RUnlock()
		_, err := LIMIT.WriteString(r.URL.Path + "\t" + r.Header.Get("X-Real-IP") + "\t" + strconv.Itoa(time.Now().Hour()) + ":" + strconv.Itoa(time.Now().Minute()) + ":" + strconv.Itoa(time.Now().Second()) + "\n")
		return err
	})
	r.Middleware("authLogin", middleware.AuthLogin)
	r.Middleware("bookAuthLogin", middleware.BookAuthLogin)
	r.Dynamic("./dev.yml")
	r.Get("/", router.Index, nil)
	r.Get("/search", router.Search, nil)
	r.Get("/auth/qr", router.AuthUrl, nil)
	r.Get("/auth/qr/connect", router.AuthConnect, nil)
	r.Group("/api", func(groups *cedar.Groups) {
		groups.Get("/article/get", router.ArticlesList, nil) // 前台文章
		groups.Get("/category/get", router.CategoryList, nil)
		groups.Post("/user_login", router.UserLogin, nil) // 用户登录
	})
	// TODO    blog api
	r.Group("/manager", func(groups *cedar.Groups) {
		groups.Get("/", router.BackendIndexPage, nil, "authLogin") // 直接后台 ,用token来判断 是否已经登录
		groups.Post("/post_article", router.PostArticle, nil, "authLogin")
		groups.Post("/post_category", router.PostCategory, nil, "authLogin")
		groups.Delete("/delete/article", router.ArticleDelete, nil, "authLogin")   // 删除一条
		groups.Delete("/delete/category", router.CategoryDelete, nil, "authLogin") // 删除一条
		groups.Group("/page", func(groups *cedar.Groups) {
			groups.Get("/index", router.BackendIndexPage, nil, "authLogin")        // 首页
			groups.Get("/login", router.BackendLoginPage, nil)                     // 登录
			groups.Get("/article", router.ManagerArticlesPage, nil, "authLogin")   // 文章界面
			groups.Get("/category", router.ManagerCategoryPage, nil, "authLogin")  // 文章界面
			groups.Get("/write", router.ManagerWriteArticlePage, nil, "authLogin") // 文章界面
		})
		groups.Group("/user", func(groups *cedar.Groups) {
			groups.Post("/in", router.AdminUserLogin, nil)        // 登录
			groups.Get("/out", router.LoginOut, nil, "authLogin") // 注销
		})
		groups.Group("/get", func(groups *cedar.Groups) {
			groups.Get("/article", router.ManagerArticlesGet, nil, "authLogin")  // 获取20条
			groups.Get("/category", router.ManagerCategoryGet, nil, "authLogin") // 获取20条
			groups.Get("/get_index", router.ManagerIndex, nil, "authLogin")
		})
	})
	r.Group("/account_book", func(g *cedar.Groups) {
		g.Get("/show", router.AccountBookShow, nil)
		g.Post("/add", router.AccountBookAdd, nil)
		g.Post("/delete", router.AccountBookDelete, nil)
	})
	r.Get("/detail/:id", router.PageDetail, nil)
	r.Group("/software", func(g *cedar.Groups) {
		g.Get("/cedar", router.SoftwareCedar, nil)
	})
	r.Get("/edit", router.EditArticle, nil)
	r.Get("/reset", func(writer http.ResponseWriter, request *http.Request, co *cedar.Core) {
		username, password, ok := request.BasicAuth()
		if !ok {
			writer.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
			writer.WriteHeader(http.StatusUnauthorized)
			return
		}
		// 验证用户名/密码
		if username != "tong" || password != "fhtdx3322" {
			http.Error(writer, "RESET: need authorized!", http.StatusUnauthorized)
			return
		}
		r.Dynamic("./dev.yml")
		writer.Write([]byte("RESET SUCCESS"))
	}, nil)

	// book
	r.AutoRegister(&router.Wechat{})
	if err := http.ListenAndServe(":8010", r); err != nil {
		log.Panicln(err)
	}
}

func byt(s string) []byte {
	rs := *(*reflect.StringHeader)(unsafe.Pointer(&s))
	return *(*[]byte)(unsafe.Pointer(&rs))
}
